package core.effects;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

import util.Logger;

/**
 * Used for the creation of particles, it recycles old particles for easy
 * re-use.
 * 
 * @author Jason
 * 
 */
public final class ParticleFactory {

	private static final HashMap<Class<? extends Effect>, Queue<Effect>> recycleBin = new HashMap<Class<? extends Effect>, Queue<Effect>>();

	private ParticleFactory() {
	}

	public static synchronized Effect createEffect(
			Class<? extends Effect> effectType, Object[] parameters) {

		Queue<Effect> q = recycleBin.get(effectType);
		if (q == null) {
			q = new LinkedList<Effect>();
			recycleBin.put(effectType, q);
		}

		Effect ret = q.poll();
		if (ret == null) {
			try {
				ret = effectType.newInstance();
			} catch (Exception e) {
				Logger.log(Logger.SEVERE, "You must supply an empty"
						+ " constructor with each particle effect.");
				e.printStackTrace();
			}
		}

		ret.construct(parameters);

		return ret;
	}

	public static synchronized void recycle(Effect e) {
		Class<? extends Effect> eClass = ((Recyclable) e).getEffectClass();
		Queue<Effect> q = recycleBin.get(eClass);
		q.add(e);
	}

}
